---
title: "OpenAI"
---

<Tabs>
  <Tab title="Python">
  <AccordionGroup>

  <Accordion title="OpenAI v1+">
  Set HELICONE_API_KEY as an environment variable
  ```python
  export HELICONE_API_KEY=<your API key>
  ```

Initialize OpenAI client. Can also be done via global client.

```python
client = OpenAI(
  api_key="your-api-key-here",  # Replace with your OpenAI API key
  base_url="http://oai.hconeai.com/v1",  # Set the API endpoint
  default_headers= {  # Optionally set default headers or set per request (see below)
    "Helicone-Auth": f"Bearer {HELICONE_API_KEY}",
  }
)
```

Send request and attach extra headers

```python
chat_completion = client.chat.completions.create(
  model="gpt-4-vision-preview",
  messages=[
      {"role": "user", "content": "Hello world!"}
  ],
  extra_headers={ # Can also attach headers per request
      "Helicone-Auth": f"Bearer {HELICONE_API_KEY}",
  },
)
```

    That's it! Your OpenAI requests now log results to Helicone.

  </Accordion>

  <Accordion title="OpenAI <v1">
  Set HELICONE_API_KEY as an environment variable
  ```python
  export HELICONE_API_KEY=<your API key>
  ```

Change the api base and add a Helicone-Auth header

```python
import openai

openai.api_base = "https://oai.hconeai.com/v1"
openai.Completion.create(
  # ...other parameters
  headers={
    "Helicone-Auth": f"Bearer {HELICONE_API_KEY}",
  }
)
```

    That's it! Your OpenAI requests now log results to Helicone.

  </Accordion>
</AccordionGroup>

  </Tab>
  <Tab title="Python (w/ package)">
    **Set HELICONE_API_KEY as an environment variable**
    ```python
    export HELICONE_API_KEY=<your API key>
    ```

    **Install the Helicone Package**
    ```python
    pip install helicone
    ```

    **Change OpenAI import to use Helicone**
    ```python
    from helicone.openai_proxy import openai # replace `import openai` with this line
    ```

    That's it! Your OpenAI requests now log results to Helicone. You can use advanced Helicone features as parameters:
    ```python
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt="What is Helicone?",
        user="alice@bob.com",
        cache=True,
        properties={"conversation_id": 12},
        rate_limit_policy={"quota": 100, "time_window": 60, "segment": "user"},
        retry=True, # retry on failure
    )
    ```

  </Tab>
  <Tab title="Node.js">
  **Set HELICONE_API_KEY as an environment variable**
    ```javascript
    export HELICONE_API_KEY=<your API key>
    ```
    
  **Change the base path and add a Helicone-Auth header**
  
  **OpenAI < V4**
    ```javascript
    import { Configuration, OpenAIApi } from "openai";

    const configuration = new Configuration({
        apiKey: process.env.OPENAI_API_KEY,
        basePath: "https://oai.hconeai.com/v1",
        baseOptions: {
          headers: {
              "Helicone-Auth": `Bearer ${process.env.HELICONE_API_KEY}`,
          },
        },
    });

    const openai = new OpenAIApi(configuration);
    ```

**OpenAI V4+**

```javascript
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: request.env.OPENAI_API_KEY,
  baseURL: "https://oai.hconeai.com/v1",
  defaultHeaders: {
    "Helicone-Auth": `Bearer ${request.env.HELICONE_API_KEY}`,
  },
});
```

  </Tab>
  <Tab title="Node.js (w/ package)">
    # Installation and Setup
    <Steps>
      <Step title="To get started, install the `helicone-openai` package">
      ```bash
      npm install @helicone/helicone
      ```
      </Step>
      <Step title="Set `HELICONE_API_KEY` as an environment variable">
       ```bash
      export HELICONE_API_KEY=sk-<your-api-key>
      ```
      <Info>You can also set the Helicone API Key in your code (See below)</Info>
      </Step>
      <Step title="Replace">
      ```typescript
      const { ClientOptions, OpenAI } = require("openai");
      ```

      with

      ```typescript
      const { HeliconeProxyOpenAI as OpenAI,
        IHeliconeProxyClientOptions as ClientOptions } = require("helicone");
      ```
      </Step>
      <Step title="Make a request">
      Chat, Completion, Embedding, etc usage is equivalent to OpenAI package.
      ```typescript
      const openai = new OpenAI({
        apiKey: process.env.OPENAI_API_KEY,
        heliconeMeta: {
          apiKey: process.env.HELICONE_API_KEY, // Can be set as env variable
          // ... additional helicone meta fields
        },
      });

      const chatCompletion = await openai.chat.completion.create({
        model: "gpt-3.5-turbo",
        messages: [{ role: "user", content: "Hello world" }],
      });

      console.log(chatCompletion.data.choices[0].message);
      ```
      </Step>
    </Steps>

    ## Send feedback
    Ensure you store the `helicone-id` header returned in the original response
    ```typescript
    const { data, response } = await openai.chat.completion.create({
      model: "gpt-3.5-turbo",
      messages: [{ role: "user", content: "Hello world" }],
    }).withResponse();

    const heliconeId = response.headers.get("helicone-id");

    await openai.helicone.logFeedback(heliconeId, HeliconeFeedbackRating.Positive) // or Negative
    ```

    #### HeliconeMeta options
    ```typescript
    interface IHeliconeMeta {
      apiKey?: string;
      properties?: { [key: string]: any };
      cache?: boolean;
      retry?: boolean | { [key: string]: any };
      rateLimitPolicy?: string | { [key: string]: any };
      user?: string;
      baseUrl?: string;
      onFeedback?: OnHeliconeFeedback; // Callback after feedback was processed
    }

    type OnHeliconeLog = (response: Response) => Promise<void>;
    type OnHeliconeFeedback = (result: Response) => Promise<void>;
    ```

  </Tab>
  <Tab title="cURL">
   **Replace the OpenAI Base url with Helicone's**
   ```
   - POST https://api.openai.com/v1
   + POST https://oai.hconeai.com/v1
   ```

**Add a Helicone-Auth header into the requests**

```
"Helicone-Auth": "Bearer HELICONE_API_KEY"
```

Here is an example cURL command:

   <Note>
   Please make sure to replace API keys with your own
   </Note>
   ```
    curl --request POST \
        --url https://oai.hconeai.com/v1/chat/completions \
        --header 'Authorization: Bearer <<YOUR_OPENAI_API_KEY>> \
        --header 'Content-Type: application/json' \
        --header 'Helicone-Auth: Bearer <<YOUR_HELICONE_API_KEY>> \
        --data '{
            "model": "gpt-3.5-turbo",
            "messages": [
                {
                    "role": "system",
                    "content": "Say Hello!"
                }
            ],
            "temperature": 1,
            "max_tokens": 10
    }'
   ```

  </Tab>
  <Tab title="Langchain">
    **Python**
    
    Change the api base and add a Helicone-Auth header
    ```python
    #  Option 1
    openai.api_base = "https://oai.hconeai.com/v1"
    llm = ChatOpenAI(
        openai_api_key='<>',
        model_kwargs={
          "extra_headers":{
            "Helicone-Auth": f"Bearer {HELICONE_API_KEY}"
          }
        }
    )
    
    # Option 2
    llm = ChatOpenAI(
        openai_api_key='<>',
        model_kwargs={
          "extra_headers":{
            "Helicone-Auth": f"Bearer {HELICONE_API_KEY}"
          }
        },
        openai_api_base="https://oai.hconeai.com/v1",
    )
    ```

    **Typescript**
    ```typescript
    const llm = new OpenAI({
      modelName: "gpt-3.5-turbo",
      configuration: {
        basePath: "https://oai.hconeai.com/v1",
        defaultHeaders: {
          "Helicone-Auth": `Bearer HELICONE_API_KEY`,
          },
        },
      });
    ```

  </Tab>
</Tabs>
